package com.books4sale.feed;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.restlet.data.MediaType;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.books4sale.admin.dto.Book;
import com.books4sale.admin.dto.tools.PMF;
import com.google.appengine.api.datastore.Query;

public class BooksInfo extends ServerResource {

	@Get("xml")
	public Representation booksInfo() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Book> results = (List<Book>) pm.newQuery(Book.class).execute();
		DomRepresentation representation = null;
		try {
			representation = new DomRepresentation(
					MediaType.TEXT_XML);
			Document doc = representation.getDocument();
			Element rootElement = doc.createElement("books");

			for (Book book : results) {
				Element bookNode = doc.createElement("book");
				Element profileNode = doc.createElement("shop");
				bookNode.setAttribute("id", book.getId().getId()+"");
				bookNode.setAttribute("name", book.getBookName());
				bookNode.setAttribute("collage", book.getBookCollage());
				bookNode.setAttribute("subject", book.getBookSubject());
				bookNode.setAttribute("price", book.getBookPrice());
				bookNode.setAttribute("date", book.getDate().toString());
				
				profileNode.setAttribute("shopName", book.getProfile().getShopName());
				profileNode.setAttribute("shopAddress", book.getProfile().getShopAddress());
				profileNode.setAttribute("shopPhone", book.getProfile().getShopPhone());
				profileNode.setAttribute("shopCity", book.getProfile().getShopCity());
				
				bookNode.appendChild(profileNode);
				rootElement.appendChild(bookNode);
			}
			
			doc.appendChild(rootElement);
			doc.normalizeDocument();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return representation;
	}
}
